<template>
    <div class="file-browser-container">
        <el-row class="height-full" :gutter="20">
            <!-- 左侧文件树 -->
            <el-col class="height-full" :span="8">
                <div class="tree-panel">
                    <el-input class="search-input" v-model="filterText" placeholder="搜索文件..." clearable prefix-icon="Search" />
                    <el-tree ref="treeRef" class="file-tree" :data="fileTree" :props="treeProps"
                        :filter-node-method="filterNode" node-key="path" :default-expanded-keys="defaultExpandedKeys" :current-node-key="currentNodeKey" highlight-current :expand-on-click-node="true"
                        @node-click="handleNodeClick">
                        <template #default="{ node, data }">
                            <span class="tree-node">
                                <el-icon :color="data.directory ? '#FFA500' : '#409EFF'">
                                    <component :is="getFileIcon(data.directory, data.path)" />
                                </el-icon>
                                <span class="node-label">{{ node.label }}</span>
                                <el-tag v-if="data.directory" size="small" effect="plain">
                                    {{ data.children?.length || 0 }}
                                </el-tag>
                                <el-button v-if="data.directory && data.path" type="text" icon="Edit" @click.stop="handleRename(data)" />
                            </span>
                        </template>
                    </el-tree>
                </div>
            </el-col>
            <!-- 右侧预览区 -->
            <el-col class="height-full" :span="16">
                <div class="preview-panel">
                    <div v-if="currentFile.imagePath" class="file-preview">
                        <div class="file-header">
                            <h3>{{ currentFile.name }}</h3>
                        </div>
                        <el-form ref="formRef" :model="currentFile" :rules="photoDataRule" label-width="100px"
                            label-position="right">
                            <!-- 新增的机构问题和保管期限字段 -->
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="单位" prop="organization">
                                        <el-select v-model="currentFile.organization" placeholder="请选择单位" filterable @change="handleOrgChange" style="width: 100%">
                                            <el-option
                                                v-for="item in organizationOptions"
                                                :key="item.value"
                                                :label="item.name"
                                                :value="item.value">
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="机构问题" prop="orgIssue">
                                        <!-- <el-select v-model="currentFile.orgIssue" placeholder="请选择机构问题" @change="setFileNumberStr" style="width: 100%">
                                            <el-option
                                                v-for="item in orgIssueOptions"
                                                :key="item.value"
                                                :label="item.name"
                                                :value="item.value">
                                            </el-option>
                                        </el-select> -->
                                         <el-input v-model="currentFile.orgIssue" @change="setFileNumberStr" placeholder="请输入机构问题"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="保管期限" prop="retentionPeriod">
                                        <el-select v-model="currentFile.retentionPeriod" placeholder="请选择保管期限" @change="setFileNumberStr" style="width: 100%">
                                            <el-option label="定期10年" value="D10"></el-option>
                                            <el-option label="定期30年" value="D30"></el-option>
                                            <el-option label="永久" value="Y"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            
                            <!-- 图片路径选择 -->
                            <el-form-item label="图片路径" prop="imagePath">
                                <el-input v-model="currentFile.imagePath" readonly>
                                </el-input>
                            </el-form-item>

                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="图片背景" prop="imageBackground">
                                        <el-input v-model="currentFile.imageBackground" />
                                    </el-form-item>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="拍摄日期" prop="shootingDate">
                                                <el-date-picker
                                                    v-model="currentFile.shootingDate"
                                                    type="date"
                                                    value-format="YYYY-MM-DD"
                                                    placeholder="请选择拍摄日期"
                                                    style="width: 100%"
                                                />
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="时间段" prop="shootingPeriod">
                                                <el-time-picker
                                                    v-model="currentFile.shootingPeriod"
                                                    format="HH:mm"
                                                    value-format="HH:mm"
                                                    placeholder="请选择时间段"
                                                    style="width: 100%"
                                                />
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-form-item label="形成日期" prop="creationDate">
                                        <el-date-picker
                                                    v-model="currentFile.creationDate"
                                                    type="date"
                                                    value-format="YYYY-MM-DD"
                                                    placeholder="请选择拍摄日期"
                                                    style="width: 100%"
                                                />
                                    </el-form-item>
                                    <el-form-item label="拍摄地点" prop="shootingLocation">
                                        <el-input v-model="currentFile.shootingLocation" />
                                    </el-form-item>

                                    <el-form-item label="事由" prop="eventReason">
                                        <el-input v-model="currentFile.eventReason" type="textarea" :rows="3" />
                                    </el-form-item>
                                    <el-form-item label="图为" prop="picIs">
                                        <el-input v-model="currentFile.picIs" />
                                    </el-form-item>

                                    <el-divider>摄影者信息</el-divider>
                                    <div v-for="(person, index) in currentFile.journalists" :key="index"
                                        class="person-item">
                                        <el-row :gutter="24">
                                            <el-col :span="16">
                                                <el-form-item
                                                    :label="index === currentFile.journalists.length - 1 ? '摄影者姓名' : `摄影者${index + 1}`"
                                                    :prop="`journalists[${index}].name`">
                                                    <el-input v-model="person.name" />
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="8">
                                                <el-button v-if="index === currentFile.journalists.length - 1"
                                                    type="primary" plain @click="addJournalist" icon="Plus">
                                                    添加
                                                </el-button>
                                                <el-button v-else type="danger" plain @click="removeJournalist(index)"
                                                    icon="Delete">
                                                    删除
                                                </el-button>
                                            </el-col>
                                        </el-row>
                                    </div>
                                </el-col>
                                <el-col :span="12">
                                    <!-- 图片预览 -->
                                    <el-form-item v-if="currentFile.imgUrl">
                                        <el-image :src="currentFile.imgUrl" :preview-src-list="[currentFile.imgUrl]"
                                            fit="contain"
                                            style="height: auto; width: auto; max-height: none; max-width: none"
                                            :zoom-rate="1.2" :preview-teleported="true">
                                            <template #error>
                                                <div class="image-slot">
                                                    <el-icon>
                                                        <Picture />
                                                    </el-icon>
                                                </div>
                                            </template>
                                        </el-image>
                                        <div
                                            style="width: 100%; display: flex; justify-content: center; align-items: center;">
                                            <span>{{ currentFile.imageName }}</span>
                                            <el-button type="text" size="small"
                                                @click="copyToClipboard(currentFile.imageName)" icon="CopyDocument"
                                                title="复制" />
                                        </div>
                                    </el-form-item>
                                    <el-form-item>
                                        <div class="label">文档内容</div>
                                        <el-input v-model="currentFile.extendedData.originalText" type="textarea"
                                            :rows="3" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-divider></el-divider>
                                <el-col :span="6">
                                    <el-form-item label="图片格式" prop="imageFormat">
                                        <el-input v-model="currentFile.imageFormat" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6">
                                    <el-form-item label="图片大小" prop="imageSize">
                                        <el-input v-model="currentFile.imageSize" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6">
                                    <el-form-item label="图片分辨率" prop="imageScale">
                                        <el-input v-model="currentFile.imageScale" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6">
                                    <el-form-item label="分辨率" prop="imageDpi">
                                        <el-input v-model="currentFile.imageDpi" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-divider>人物信息</el-divider>

                            <div v-for="(person, index) in currentFile.persons" :key="index" class="person-item">
                                <el-row :gutter="20">
                                    <el-col :span="6">
                                        <el-form-item :label="index === currentFile.persons.length - 1 ? '人物位置' : ''"
                                            :prop="`persons[${index}].positionInImage`">
                                            <el-input v-model="person.positionInImage" placeholder="如: 中1, 左1" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="6">
                                        <el-form-item :label="index === currentFile.persons.length - 1 ? '姓名' : ''"
                                            :prop="`persons[${index}].name`">
                                            <el-input v-model="person.name" @change="searchPositionByName(index)" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="6">
                                        <el-form-item :label="index === currentFile.persons.length - 1 ? '职务' : ''"
                                            :prop="`persons[${index}].position`">
                                            <el-input v-model="person.position" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="6">
                                        <el-button v-if="index === currentFile.persons.length - 1" type="primary" plain
                                            @click="addPerson" icon="Plus">
                                            添加
                                        </el-button>
                                        <el-button v-else type="danger" plain @click="removePerson(index)"
                                            icon="Delete">
                                            删除
                                        </el-button>
                                    </el-col>
                                </el-row>
                            </div>

                            <el-divider>题名设置</el-divider>
                            <el-row>
                                <el-col :span="20">
                                    <el-form-item label="合成题名" prop="compositeTitle">
                                        <el-input :disabled="isLockCompositeTitle" v-model="currentFile.compositeTitle"
                                            type="textarea" :rows="3" />
                                        <el-button type="text" size="small"
                                            @click="copyToClipboard(currentFile.compositeTitle)"
                                            title="复制">复制</el-button>
                                        <div class="lock-icon">
                                            <el-tooltip class="box-item" effect="dark"
                                                :content="isLockCompositeTitle ? '当前合成题名已锁定' : '点击锁定当前合成题名，可自动复制到下一页'"
                                                placement="right-end"><el-icon @click="toggleLockStatus"
                                                    style="cursor: pointer;">
                                                    <Lock style="color:#409eff;" v-if="isLockCompositeTitle" />
                                                    <Unlock v-else />
                                                </el-icon></el-tooltip>
                                        </div>
                                    </el-form-item>
                                    <el-form-item label="图片题名" prop="imageTitle">
                                        <el-input v-model="currentFile.imageTitle" type="textarea" :rows="3" />
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-form-item class="form-actions">
                                <!-- 下一个文件夹的第一张图 -->
                                <el-button @click="handleNextDir">下一件</el-button>
                                <!-- 当前文件夹的下一张图 -->
                                <el-button @click="handleNextPic">下一页</el-button>
                                <el-button type="primary" @click="submitForm">提交</el-button>
                            </el-form-item>
                            <el-form-item label="是否移馆" prop="isMovedToArchive">
                                <el-radio-group v-model="currentFile.isMovedToArchive">
                                    <el-radio :value="true">是</el-radio>
                                    <el-radio :value="false">否</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="档号" prop="fileNumber">
                                <el-input v-model="currentFile.fileNumber" />
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, computed, onUnmounted } from 'vue'
import {
    Picture,
    Tickets,
    VideoPlay,
    Folder,
    Document,
    Edit  // 引入编辑图标
} from '@element-plus/icons-vue'
import { getFileTree, searchNewsPhotos, createNewsPhoto, postRenameFolder } from '@/api/newsPhotos'
import { searchPersonPosition, addPersonPosition } from '@/api/personPosition'
import { ElMessage, ElMessageBox } from 'element-plus'
import { parseDateToChineseWithValidation, convertTimeToPeriod } from '@/utils/timeUtil'
import { flattenTree, replacePictureDescription, copyToClipboard, handlePersonPositionData, isSameDirectory, isImgByPath, normalizeImagePath, parseImagePath, getOrgIssueData, extractDateFromPath, isMediaByPath } from '@/utils/fileUtil'
import { useNewsStore } from '@/stores/newsStore'
import { useRoute, useRouter } from 'vue-router'
import { getUnits } from '@/api/unitManagement'
import { file } from 'jszip'
const route = useRoute()
const router = useRouter()
// 文件树数据
const fileTree = ref([])
const currentFile = ref({})
const curCompositeTitle = ref('')
const formRef = ref()
const filterText = ref('')
const treeRef = ref()
const currentNodeKey = ref('')
const defaultExpandedKeys = ref([])
const orgIssueData = ref({})
const floderData = ref({
    path: '',
    isSet: false,
    imageBackground: '',
    shootingLocation: '',
    organization: '',
    journalists: [{ name: '' }],
    extendedData: {
        originalText: '',
    },
    compositeTitle: '',
    retentionPeriod: '',
    orgIssue: ''
})

// 机构问题选项数据
const orgIssueOptions = ref([
  { name: '领导人活动类', value: 'WLD' },
  { name: '时政要闻类', value: 'WSZ' },
  { name: '经济类', value: 'WJJ' },
  { name: '社会类', value: 'WSH' },
  { name: '教育类', value: 'WJY' },
  { name: '娱乐文化类', value: 'WYL' },
  { name: '军事类', value: 'WJS' },
  { name: '城市建设类', value: 'WCJ' },
  { name: '体育类', value: 'WTY' },
  { name: '文化遗产类', value: 'WWH' },
  { name: '医疗卫生类', value: 'WYW' },
  { name: '公检法类', value: 'WGJ' },
  { name: '农业农村类', value: 'WNY' },
  { name: '科技类', value: 'WKJ' },
  { name: '港澳台交流类', value: 'WGA' },
  { name: '报社活动类', value: 'WBS' }
])

// 单位选项数据
const organizationOptions = ref([])

// 树形配置
const treeProps = {
    label: 'name',
    children: 'children'
}

const newsStore = useNewsStore()
// const news = computed(() => newsStore.currentNews)
// watch(news, (newVal) => {
//     if (newVal) {
//         // 深拷贝
//         const imagePath = JSON.parse(JSON.stringify(newVal.imagePath))
//         const defaultTreeData = parseImagePath(imagePath)
//         defaultExpandedKeys.value = defaultTreeData.defaultExpandedKeys
//         currentNodeKey.value = defaultTreeData.currentNodeKey
//         handleNodeClick({ ...newVal, path: newVal.imagePath ? normalizeImagePath(newVal.imagePath) : '' })
//     }
// }, { immediate: true })

const photoDataRule = {
    shootingDate: [{ required: true, message: '请选择日期', trigger: 'change' }],
    shootingPeriod: [{}]
}

// 监听query参数
watch(() => route.query, async (newVal) => { 
    if (newVal.path) {
        const imagePath = JSON.parse(JSON.stringify(newVal.path))
        const defaultTreeData = parseImagePath(imagePath)
        defaultExpandedKeys.value = defaultTreeData.defaultExpandedKeys
        currentNodeKey.value = defaultTreeData.currentNodeKey
        handleNodeClick({ path: defaultTreeData.currentNodeKey })
    }
}, { immediate: true })

// 更新单位信息
const handleOrgChange = (val) => {
    const data = organizationOptions.value.find(item => item.value === val)
    if (data) {
        currentFile.value.orgIssue = data.orgIssue
        currentFile.value.retentionPeriod = data.retentionPeriod
    }
    orgIssueData.value = data
    setFileNumberStr()
}

const getCurrentOrgIssueData = async (val) => {
    if (!val) return
    if (organizationOptions.value.length === 0) {
        const unitRes = await getUnits()
        organizationOptions.value = unitRes.map(item => {
            return {
                name: item.unit_name,
                value: item.id + '',
                ...item
            }
        })
    }
    console.log('-------', orgIssueOptions.value)
    const data = organizationOptions.value.find(item => item.value === val)
    orgIssueData.value = data
}

// 设置档号
const setFileNumberStr = async () => {
    let fileNumberStr = ''
    let yearStr = ''
    let formattedIndex = '0001'
    console.log('orgIssueData.value', orgIssueData.value)
    // 保存单位信息
    if (!orgIssueData.value?.recordGroupNum) {
        await getCurrentOrgIssueData(currentFile.value.organization)
    }
    yearStr = defaultExpandedKeys.value[1]
    fileNumberStr = `${orgIssueData.value.recordGroupNum}-${currentFile.value.fileType}•${yearStr}-${currentFile.value.retentionPeriod}-${currentFile.value.orgIssue}-`
    // 1. 扁平化文件树，便于查找
    if (fileTree.value.length === 0) {
        const res = await getFileTree()
        fileTree.value = [res] // 将根节点包装为数组
    }
    const flatFiles = flattenTree(fileTree.value)
    const currentFolder = flatFiles.find(item => item.path === yearStr)
    // const currentIndex = currentFolder.children.findIndex(file => file.path === currentFile.value.path)
    // 递归需找 currentFolder.children 的所有子文件， directory = false 的数据
    const subFiles = []
    const findSubFiles = (children) => {
        children.forEach(item => {
            if (item.directory) {
                findSubFiles(item.children)
            } else {
                // 过滤非图片的数据
                if (!isImgByPath(item.name)) return
                subFiles.push(item)
            }
        })
    }
    findSubFiles(currentFolder.children)
    const currentIndex = subFiles.findIndex(file => file.path === currentFile.value.path)
    if (fileNumberStr) {
        formattedIndex = (currentIndex + 1).toString().padStart(4, '0')// 格式化为四位数序号，如 0001, 0002, ..., 0100
        currentFile.value.fileNumber = fileNumberStr + formattedIndex
    }
    currentFile.value.fileNumber = fileNumberStr ? fileNumberStr + formattedIndex : ''
}

// 加载文件树
const loadFileTree = async (isReload) => {
    try {
        if (fileTree.value.length === 0 || isReload) {
            const res = await getFileTree()
            fileTree.value = [res] // 将根节点包装为数组
        }
        
        // 加载机构问题选项数据
        orgIssueOptions.value = getOrgIssueData()
        
        // 使用 getUnits API 获取单位数据
        const unitRes = await getUnits()
        organizationOptions.value = unitRes.map(item => {
            return {
                name: item.unit_name,
                value: item.id + '',
                ...item
            }
        })
        console.log('-------', organizationOptions.value)
    } catch (error) {
        // ElMessage.error('加载文件树失败: ' + error.message)
    }
}

// 处理节点点击
async function handleNodeClick(data) {
    if (data.directory) return
    if (data.path) {
        // 修改当前地址query 参数
        if (route.query.path !== data.path) {
            // 只做地址修改， 不跳转
            router.replace({
                query: {
                    path: data.path
                }
            })
        }
    }
    if (isImgByPath(data.path) || isMediaByPath(data.path)) {
        currentFile.value = {
            ...data,
            persons: [{ positionInImage: '', name: '', position: '' }],
            journalists: [{ name: '' }],
            extendedData: {
                originalText: '',
            },
            imgUrl: import.meta.env.VITE_API_BASE_URL + '/static/' + data.path,
            orgIssue: '',        // 添加机构问题默认值
            retentionPeriod: ''  // 添加保管期限默认值
        }

        // 先根据图片全路径，在数据库中查询是否已有填写信息，有的话返显
        // 若无数据，则获取图片的exif数据，按照自动填充的逻辑实现填充
        if (!data.path) return;
        let response
        let imgPath = import.meta.env.VITE_API_FOLDER_NAME + data.path
        if (/^[A-Za-z]:\\/.test(imgPath)) {
            // 将 / 转换为 \
            imgPath = imgPath.replace(/\//g, '\\')
        }
        response = await searchNewsPhotos({
            imagePath: imgPath
        })
        if (!response || !response.content || response.content.length === 0) return;
        const matchRes = response.content[0];
        try {
            matchRes.extendedData = JSON.parse(matchRes.extendedData)
            matchRes.persons = matchRes.extendedData?.persons || []
            matchRes.journalists = matchRes.journalists?.split(',').map(item => {
                return { name: item }
            }) || [{ name: '' }]
        } catch (error) {
            console.log(error)
        }
        currentFile.value = { ...currentFile.value, ...matchRes }
        if (!currentFile.value.extendedData) currentFile.value.extendedData = { originalText: ''}
        currentFile.value.persons.push({ positionInImage: '', name: '', position: '' });
        if (!currentFile.value.compositeTitle) {
            setCompositeTitle()
        }

        const date = extractDateFromPath(imgPath)
        // 判断date是否为日期
        if (date) {
            currentFile.value.shootingDate = date
        }

        const floderData = getCurrentFloderData(data.path)
        floderData.value = floderData
        if (floderData.value.isSet) {
            currentFile.value.imageBackground = floderData.value.imageBackground
            currentFile.value.shootingLocation = floderData.value.shootingLocation
            currentFile.value.organization = floderData.value.organization
            currentFile.value.journalists = floderData.value.journalists
            currentFile.value.extendedData.originalText = floderData.value.extendedData.originalText
            currentFile.value.compositeTitle = floderData.value.compositeTitle
            if (currentFile.value.organization) handleOrgChange(currentFile.value.organization)
            currentFile.value.retentionPeriod = floderData.value.retentionPeriod
            currentFile.value.orgIssue = floderData.value.orgIssue
        }
    } else {
        // 目前只支持服务器所在电脑的本地路径打开
        // TODO: 需要先检查是否存在该文件，若不存在，需调用接口（后端要新增一个接口），将该文件传输到指定目录下再打开
        try{
            if (window.electronAPI.openFile) {
                const fullPath = (import.meta.env.VITE_API_FOLDER_NAME || 'E:\\相片档案\\') + data.path
                const normalizedPath = fullPath.replace(/\\/g, '/');
                window.electronAPI.openFile(normalizedPath)
            } else {
                let fileUrl = import.meta.env.VITE_API_BASE_URL + '/static/' + data.path
                window.open(fileUrl)
            }
       }catch(error){
            ElMessage.error('打开文件失败: ' + error.message)
        }
    }
}

const fileIcons = {
    directory: Folder,         // 文件夹
    image: Picture,           // 图片
    document: Document,       // Word/文档
    pdf: Tickets,             // PDF
    video: VideoPlay,         // 视频
}


const getFileIcon = (isDirectory, path) => {
    if (isDirectory) return fileIcons.directory;
    // 如果是文件，根据扩展名返回对应图标
    const extension = path?.split('.').pop().toLowerCase();
    switch (extension) {
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'gif':
        case 'bmp':
        case 'webp':
            return fileIcons.image;
        case 'doc':
        case 'docx':
            return fileIcons.document;
        case 'pdf':
            return fileIcons.pdf;
        case 'mp4':
        case 'avi':
        case 'mov':
            return fileIcons.video;
        case 'mp3':
        case 'wav':
            return fileIcons.audio;
        case 'zip':
        case 'rar':
        case '7z':
            return fileIcons.zip;
        default:
            return Document; // 默认文档图标
    }
}

// 树形过滤
const filterNode = (value, data) => {
    if (!value) return true
    return data.name.toLowerCase().includes(value.toLowerCase())
}

const isLockCompositeTitle = ref(false)
// 合成题名={时间+（时间段）中间用“，”隔开}+人物（多个人物中间用“、”隔开，人物这间的位置用“（）”）+地点+事由+图为（图为内容要加（））+单位+摄影者（多个摄影都中间用空格隔开）+摄字（单位 摄影者 摄 三者之间用空格隔开）
function concatTitle() {
    const date = parseDateToChineseWithValidation(currentFile.value.shootingDate || '') + convertTimeToPeriod(currentFile.value.shootingPeriod || '');
    const personStr = currentFile.value.persons.filter(item => item.name)
        .map(item => item.position + item.name + (item.positionInImage ? ('(' + item.positionInImage + ')') : '')).join('、');
    const location = currentFile.value.shootingLocation ? ('在' + currentFile.value.shootingLocation + '，') : '';
    const eventReason = currentFile.value.eventReason + '。';
    const picStr = currentFile.value.picIs ? `（图为${currentFile.value.picIs}）` : '';
    currentFile.value.journalists = currentFile.value.journalists || [{ name: '' }]
    let orgStr = ''
    if (currentFile.value.organization) {
        //获取单位名称 organizationOptions
        const orgItem = organizationOptions.value.find(item => item.value === currentFile.value.organization)
        orgStr = orgItem?.name || ''
    }
    const journalistStr = orgStr + ' ' + currentFile.value.journalists.map(item => item.name).join(' ')
    const takeOperation = journalistStr.trim() ? ' 摄' : '';
    console.log(date + personStr + location + eventReason + picStr + journalistStr + takeOperation)
    return date + personStr + location + eventReason + picStr + journalistStr + takeOperation;
}

function setCompositeTitle() {
    if (isLockCompositeTitle.value) {
        currentFile.value.compositeTitle = replacePictureDescription(curCompositeTitle.value, currentFile.value.picIs)
    } else {
        currentFile.value.compositeTitle = concatTitle();
        console.log(currentFile.value.compositeTitle);
    }
}

// 添加/删除人物
const addPerson = () => {
    currentFile.value.persons.push({ positionInImage: '', name: '', position: '' })
}
const removePerson = (index) => {
    currentFile.value.persons.splice(index, 1)
}
const addJournalist = () => {
    currentFile.value.journalists.push({ name: '' })
}
const removeJournalist = (index) => {
    currentFile.value.journalists.splice(index, 1)
}

function handleNextPic() {
    if (!currentFile.value || !currentFile.value.path || !fileTree.value?.length) return;

    // 1. 扁平化文件树，便于查找
    const flatFiles = flattenTree(fileTree.value);

    // 2. 找到当前选中文件的索引
    const currentIndex = flatFiles.findIndex(file => file.path === currentFile.value.path);

    if (currentIndex === -1) return;
    
    const currentData = JSON.parse(JSON.stringify(currentFile.value))
    // 3. 查找下一个文件（跳过文件夹）
    let nextIndex = currentIndex + 1;
    while (nextIndex < flatFiles.length) {
        const nextFile = flatFiles[nextIndex];
        if (!nextFile.directory && isImgByPath(nextFile.path)) {
            // 判断currentData.path 与 nextFile.path 是否在同一个目录下
            if (isSameDirectory(currentData.path, nextFile.path)) {
                setFloder(currentData)
                handleNodeClick(nextFile)
            } else {
                // 重置原始数据
                resetFloder()
                handleNodeClick(nextFile)
            }
            return;
        }
        nextIndex++;
    }

    // 如果后面没有文件了，可以循环到第一个或给出提示
    ElMessage.primary(`已是最后一个文件`);

}


function handleNextDir() {
    if (!currentFile.value || !currentFile.value.path || !fileTree.value?.length) return;

    // 1. 扁平化文件树，便于查找
    const flatFiles = flattenTree(fileTree.value);

    // 2. 找到当前选中文件的索引
    const currentIndex = flatFiles.findIndex(file => file.path === currentFile.value.path);

    if (currentIndex === -1) return;

    // 3. 查找下一个目录
    let nextIndex = currentIndex + 1;
    while (nextIndex < flatFiles.length) {
        const nextFile = flatFiles[nextIndex];
        if (!nextFile.directory && isImgByPath(nextFile.path) && !isSameDirectory(nextFile.path, currentFile.value.path)) {
            // 找到下一个目录，触发选择
            handleNodeClick(nextFile)
            return;
        }
        nextIndex++;
    }
    // 重置原始数据
    resetFloder()

    // 如果后面没有目录了，可以循环到第一个或给出提示
    ElMessage.primary(`已是最后一个目录`);
}

// 重置原始数据
const resetFloder = () => {
    console.log('重置')
    floderData.value = {
        path: '',
        isSet: false,
        imageBackground: '',
        shootingLocation: '',
        organization: '',
        journalists: [{ name: '' }],
        extendedData: {
            originalText: '',
        },
        compositeTitle: '',
        retentionPeriod: '',
        orgIssue: ''
    }
    // 存储到本地缓存
    localStorage.setItem('floderData', JSON.stringify(floderData.value))
}

const setFloder = (data) => {
    floderData.value = {
        path: data.path,
        isSet: true,
        imageBackground: data.imageBackground || '',
        shootingLocation: data.shootingLocation || '',
        organization: data.organization || '',
        journalists: data.journalists || [],
        extendedData: {
            originalText: data.extendedData?.originalText || '',
        },
        compositeTitle: data.compositeTitle || '',
        retentionPeriod: data.retentionPeriod || '',
        orgIssue: data.orgIssue || ''
    }
    console.log('设置', floderData)
    // 存储到本地缓存
    localStorage.setItem('floderData', JSON.stringify(floderData.value))
}

const getCurrentFloderData = (path) => {
    const data = JSON.parse(localStorage.getItem('floderData') || '{}')
    console.log('获取', data, path)
    if (isSameDirectory(data.path, path)) {
        return data
    } else {
        resetFloder()
        return floderData.value
    }
}

const searchPositionByName = async (index) => {
    const name = currentFile.value.persons[index].name;
    if (name) {
        const result = await searchPersonPosition({ name });
        currentFile.value.persons[index].position = result.map(item => item.positionTitles).join('、');
    }
}

const savePersonPosition = async (data) => {
    if (!data) return;
    // 调用接口保存到姓名职务表
    await addPersonPosition(data);
}

// 表单提交
const submitForm = async () => {
    try {
        await formRef.value.validate()
        const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
        const operatorId = userInfo.value.userId || null
        if (!operatorId) {
            ElMessage.error('操作员信息未找到，请先登录')
            return
        }
        // 更新姓名职务表
        const persons = [];
        currentFile.value.persons.forEach(item => {
            const { name, position, positionInImage } = item;
            if (!name || !position) return;
            const data = handlePersonPositionData(item);
            savePersonPosition(data);
            persons.push(item);
        })
        currentFile.value.extendedData.persons = persons;
        const postData = {
            ...currentFile.value,
            journalists: currentFile.value.journalists.map(item => item.name).join(','),
            extendedData: JSON.stringify(currentFile.value.extendedData)
        }
        console.log('提交数据:', postData)
        const result = await createNewsPhoto(postData, operatorId)
        if (result) {
            // 提交成功需要清空数据，否则刷新完还是旧内容
            resetFloder()
            ElMessage.success('保存成功')
        } else {
            ElMessage.error('保存失败:' + result)
        }
    } catch (error) {
        ElMessage.error(error.message || '提交失败, 请补充拍摄日期')
        console.error('表单验证失败:', error)
    }
}


// 监听搜索词变化
watch(filterText, (val) => {
    treeRef.value?.filter(val)
})

watch(
    () => [
        currentFile.value.shootingDate,
        currentFile.value.shootingPeriod,
        currentFile.value.persons,
        currentFile.value.shootingLocation,
        currentFile.value.eventReason,
        currentFile.value.picIs,
        currentFile.value.organization,
        currentFile.value.journalists
    ],
    () => {
        if (!isLockCompositeTitle.value) {
            currentFile.value.compositeTitle = concatTitle();
        } else {
            currentFile.value.compositeTitle = replacePictureDescription(currentFile.value.compositeTitle, currentFile.value.picIs)
        }
    },
    { deep: true }
);

function toggleLockStatus() {
    isLockCompositeTitle.value = !isLockCompositeTitle.value
    if (isLockCompositeTitle.value) {
        curCompositeTitle.value = currentFile.value.compositeTitle
    }
    console.log(curCompositeTitle.value)
}

// 添加重命名处理函数
const handleRename = (data) => {
    ElMessageBox.prompt('请输入新的文件夹名称', '重命名', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: data.name
    }).then(async ({ value }) => {
        if (!value || value === data.name) return
        
        try {
            // 使用 postRenameFolder 接口方法替换直接的 fetch 调用
            const result = await postRenameFolder({
                oldPath: window.electronAPI.openFil ? data.path : import.meta.env.VITE_API_FOLDER_NAME + data.path,
                newFolderName: value
            })
            
            if (result) {
                ElMessage.success('重命名成功')
                // 更新树节点显示名称
                data.name = value
                // 重新加载文件树以确保数据一致性
                await loadFileTree(true)
            } else {
                ElMessage.error('重命名失败')
            }
        } catch (error) {
            ElMessage.error('重命名失败: ' + error.message)
        }
    }).catch(() => {
        // 用户取消操作
    })
}

// 初始化加载
onMounted(async () => {
    await loadFileTree()
})

// 添加页面销毁前的处理逻辑
onUnmounted(() => {
    console.log('页面销毁')
    // resetFloder()
})
</script>

<style scoped>
.file-browser-container {
    height: calc(100vh - 140px);
    background-color: #f5f7fa;
    overflow: hidden;
}

.height-full {
    height: 100%;
}

.tree-panel {
    background-color: #fff;
    border-radius: 4px;
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
}

.search-input {
    padding: 15px 15px 0;
}

.file-tree {
    flex: 1;
    padding: 15px;
    overflow: auto;
}

.preview-panel {
    background-color: #fff;
    border-radius: 4px;
    height: 100%;
    overflow-y: auto;
}

.tree-node {
    display: flex;
    align-items: center;
    width: 100%;
}

.node-label {
    margin-left: 6px;
    margin-right: 8px;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.file-preview {
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: 20px;
}

.file-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
}

.image-preview {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
}

.image-preview .el-image {
    max-width: 100%;
    max-height: 80vh;
}

.text-preview {
    flex: 1;
}

.text-preview pre {
    white-space: pre-wrap;
    font-family: monospace;
    background: #f8f8f8;
    padding: 15px;
    border-radius: 4px;
    margin: 0;
}

.unsupported-preview,
.empty-preview {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #909399;
}

.unsupported-preview .el-icon,
.empty-preview .el-icon {
    font-size: 60px;
    margin-bottom: 20px;
}

.empty-preview p {
    margin-top: 10px;
}
</style>